package wxapp

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"time"
)

type WxSessionData struct {
	WxApiRet
	OpenId string `json:"openid"`
	UnionId string `json:"unionid"`
	Sessionkey string `json:"session_key"`
}

func GenSessionString(openid string, hash_key string) string {
	tmstr := fmt.Sprintf("%d", time.Now().Unix())
	paramstr := fmt.Sprintf("%s%s%s", tmstr, openid, hash_key)
	md5 := md5.Sum([]byte(paramstr))
	md5str := fmt.Sprintf("%x", md5)
	return fmt.Sprintf("%s-%s", tmstr, md5str)
}

//登录凭证校验。
//通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。
//根据code获取opendid以及session_key
func GetOpenIdByCode(appid string, secret string, code string) (WxSessionData, error) {
	wx_addr := "https://api.weixin.qq.com/sns/jscode2session"
	wx_addr = fmt.Sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%s",
		wx_addr, appid, secret, code, "authorization_code")

	var ent WxSessionData
	res, err := WxApiGet(wx_addr)
	if err != nil {
		return ent, err
	}

	err = json.Unmarshal(res, &ent)
	if err != nil {
		return ent, err
	}

	return ent, nil
}
